package com.fabric.contract;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.hyperledger.fabric.gateway.Contract;
import org.hyperledger.fabric.gateway.Gateway;
import org.hyperledger.fabric.gateway.Identities;
import org.hyperledger.fabric.gateway.Network;
import org.hyperledger.fabric.gateway.Wallet;
import org.hyperledger.fabric.gateway.Wallets;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.BufferedReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;

@Configuration
@AllArgsConstructor
@Slf4j
public class HyperLedgerFabricGatewayConfig {

    final HyperLedgerFabricProperties hyperLedgerFabricProperties;

    @Bean
    public Gateway gateway() throws Exception {
        // Log paths for debugging
        log.info("Certificate Path: {}", hyperLedgerFabricProperties.getCertificatePath());
        log.info("Private Key Path: {}", hyperLedgerFabricProperties.getPrivateKeyPath());

        // Read the certificate and private key
        BufferedReader certificateReader = Files.newBufferedReader(Paths.get(hyperLedgerFabricProperties.getCertificatePath()), StandardCharsets.UTF_8);
        X509Certificate certificate = Identities.readX509Certificate(certificateReader);

        BufferedReader privateKeyReader = Files.newBufferedReader(Paths.get(hyperLedgerFabricProperties.getPrivateKeyPath()), StandardCharsets.UTF_8);
        PrivateKey privateKey = Identities.readPrivateKey(privateKeyReader);

        // Set up Wallet and Gateway connection
        Wallet wallet = Wallets.newInMemoryWallet();
        wallet.put("user1", Identities.newX509Identity("Org1MSP", certificate, privateKey));

        Gateway.Builder builder = Gateway.createBuilder()
                .identity(wallet, "user1")
                .networkConfig(Paths.get("src/main/resources/org1TestNetworkConnection.json"));
        Gateway gateway = builder.connect();

        log.info("=========================================== connected fabric gateway {} " , gateway);
        return gateway;
    }


    @Bean
    public Contract contract(Gateway gateway) {

        // 获取通道
        Network network = gateway.getNetwork("mychannel");

        // 获取合约
        return network.getContract("contract_chaincode");
    }
}

//    @Bean
//    public ChaincodeEventListener chaincodeEventListener(Network network) {
//        return new ChaincodeEventListener(network);
//    }
//}
